/*
 * uart_process.c
 *
 *  Created on: 2025-07-06
 *      Author: Grasping
 */

#include "My_INC/APP/uart_process.h"
#include "My_INC/APP/device_handlers.h"
#include "My_INC/PHY/PHY_Print.h"
#include "My_INC/APP/uart_comm.h"
#include <string.h> // 添加string.h头文件用于memcpy

// 常量定义
#define MAX_DATA_SIZE 256 // 最大数据长度
#define BUF_SIZE 512      // 缓冲区大小

// 外部声明
extern UART_DMA_BufferTypeDef Uart2_DMA_Buffer; // 数据通信串口2环形缓冲区管理结构

/* 函数声明 */
static void process_command(const uart_frame_t *frame);
static int send_command(uint8_t cmd_type, uint16_t *data, uint8_t data_len);

// 串口2接收数据，由串口一打印调试
void UART2_ProcessData(void)
{
    // 读取串口2环形缓冲区数据
    uint8_t temp_buffer[MAX_SIZE];
    uint16_t data_size = UART_ReadData(&Uart2_DMA_Buffer, temp_buffer, MAX_SIZE - 1);

    if (data_size > 0)
    {
        // 打印接收到的原始数据
        Uart1_Printf("Received Frame (%d bytes): ", data_size);
        for (uint16_t i = 0; i < data_size; i++)
        {
            Uart1_Printf("%02X ", temp_buffer[i]);
        }
        Uart1_Printf("\r\n");

        // 解码帧数据
        uart_frame_t decoded_frame;
        int decode_result = uart_decode_frame(temp_buffer, data_size, &decoded_frame);

        if (decode_result == 0)
        {
            // 处理解析后的命令
            process_command(&decoded_frame);
        }
        else
        {
            Uart1_Printf("数据解析失败，错误码: %d\r\n", decode_result);
        }
    }
}

// 处理接收到的命令
static void process_command(const uart_frame_t *frame)
{
    if (frame == NULL)
    {
        return;
    }

    // 查找命令处理器
    const cmd_handler_entry_t *handler = find_cmd_handler(frame->cmd);
    if (handler == NULL)
    {
        Uart1_Printf("未找到命令处理器: 0x%02x\r\n", frame->cmd);
        return;
    }

    // 检查数据长度
    if (frame->length < handler->min_length)
    {
        Uart1_Printf("命令0x%02x数据长度不足: 需要%d, 实际%d\r\n",
                     frame->cmd, handler->min_length, frame->length);
        return;
    }

    // 执行命令处理
    cmd_result_t result = handler->handler(frame->data, frame->length);
    if (result != CMD_SUCCESS)
    {
        Uart1_Printf("命令0x%02x处理失败: %d\r\n", frame->cmd, result);
    }
}

// 发送命令函数
static int send_command(uint8_t cmd_type, uint16_t *data, uint8_t data_len)
{
    if (data == NULL && data_len > 0)
    {
        Uart1_Printf("发送数据参数错误\r\n");
        return -1;
    }

    uart_encode_params_t params = {
        .data = data,
        .data_len = data_len,
        .cmd = cmd_type,
        .direction = FRAME_DIR_STM32_TO_ESP32,
    };

    uint8_t frame[BUF_SIZE];
    uint8_t frame_len;

    int ret = uart_encode_frame(&params, frame, &frame_len);
    if (ret != 0)
    {
        Uart1_Printf("帧编码失败: %d\r\n", ret);
        return -1;
    }

    // 打印发送的数据（调试用）
    // Uart1_Printf("发送帧数据 (命令:0x%02X, 长度:%d): ", cmd_type, frame_len);
    // for (uint16_t i = 0; i < frame_len; i++)
    // {
    //     Uart1_Printf("%02X ", frame[i]);
    // }
    // Uart1_Printf("\r\n");

    // 发送数据
    UART2_DMA_Send(frame, frame_len);
    return 0;
}

// 同步数据 - 电压和电流
int send_realCurrentVoltage_command(uint16_t voltage, uint16_t current)
{
    uint16_t data[2] = {voltage, current};
    return send_command(CMD_VOLTAGE_CURRENT_SIGNAL, data, 2);
}

// 同步数据 - 有功和无功
int send_realPQ_command(uint16_t p, uint16_t q)
{
    uint16_t data[2] = {p, q};
    return send_command(CMD_PQ_SIGNAL, data, 2);
}

// 同步数据 - 频率和功率因数
int send_realFUPF_command(uint16_t f, uint16_t pf)
{
    uint16_t data[2] = {f, pf};
    return send_command(CMD_FUPF_SIGNAL, data, 2);
}

// 同步数据 - 开关状态
int send_realSwitch_command(bool on)
{
    uint16_t data[1] = {on ? 1 : 0};
    return send_command(CMD_SWITCH_SIGNAL, data, 1);
}

// 同步数据 - 主模式
int send_realMainMode_command(uint8_t mainMode)
{
    uint16_t data[1] = {mainMode};
    return send_command(CMD_MODE_SWITCH, data, 1);
}

// 同步模式 - 载模式子模式
int send_realSubMode_command(uint8_t subMode)
{
    uint16_t data[1] = {subMode};
    return send_command(CMD_EL_MODE_SWITCH, data, 1);
}
